package w83a.w83aOperacionesPaso.w83aLotesPreavisos;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.sql.Blob;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import w83a.w83aBeans.W83aLotesPreavisosBean;
import w83a.w83aUtilidadesComunes.W83aClsTrazas;

import es.ejie.frmk.presentacion.operacion.paso.Q70ActionPasoOP;
import es.ejie.frmk.presentacion.sesiondatos.Q70ContextoEJIE;

public class W83aDescargarFicheroVueltaContextoOPAction extends Q70ActionPasoOP {

	protected void processOP(Q70ContextoEJIE contexto, ActionErrors errores, ActionMapping mapping,
			ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
	}

	protected ActionForward processForward(Q70ContextoEJIE contexto, ActionErrors errors, ActionMapping mapping, 
			ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {

		W83aClsTrazas.trazaDebug(null, "@@@@ W83aDescargarFicheroVueltaContextoOPAction @@@");
		

				
		Blob documento=(Blob)contexto.get("ficheroVuelta");
		
		W83aLotesPreavisosBean bean = (W83aLotesPreavisosBean)contexto.get("w83aLotesPreavisosNuevoTempBean");
		
		InputStream in=documento.getBinaryStream();
		
		ServletOutputStream out = response.getOutputStream();
		
		//se vuelcan los bytes a una variable pero en el documento en sí, el input se va a vaciar,
		byte[] bytes=IOUtils.toByteArray(in);
	
		in.close();
		
		response.setContentType("application/octet-stream");
	    response.setHeader("Content-Disposition","attachment;filename="+bean.getNombreFicheroVuelta());
		
	   for(int i=0;i<bytes.length;i++)
	   {
		   out.write(bytes[i]);
	   }
		   
	 //para no perder el inputStream del docuemtno, volcamos los bytes al documento en sí
	   ByteArrayInputStream in2= new ByteArrayInputStream(bytes);
	   in2.close();
	   contexto.set("documentoStream",(InputStream) in2);
	   
	   out.flush();
	   out.close();
	
	   return null;
	}
}

